package edu.mobbuzz.rss.reader;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

import edu.mobbuzz.daf.bean.Logs;
import edu.mobbuzz.daf.bean.Subscriber;
import edu.mobbuzz.messaging.Messaging;
import edu.mobbuzz.web.facade.SchedularFacade;

public class FeedReader {  
	SyndFeed feed;  
	String url;  
	int numEntries;  
	FeedEntry entry[];  
	public String newline = System.getProperty("line.separator");  
	
	private SchedularFacade schedularFacade;
	private Messaging messaging;
	
	public SchedularFacade getSchedularFacade() {
		if(schedularFacade==null)
			schedularFacade = new SchedularFacade();
		return schedularFacade;
	}

	public FeedReader(String _url, Messaging _messaging) {  
		url=_url;  
		messaging = _messaging;
		updateRss();
		
   }
	
	public void updateRss(){
		try {
			  
			feed=new SyndFeedInput().build(new XmlReader(new URL(url)));  
    		    	
			List entrl = feed.getEntries();  
			Object [] entries = entrl.toArray();  
			numEntries = entries.length;  
   
			entry = new FeedEntry[numEntries];  
			
			List<Subscriber> subscriberList = getSchedularFacade().getSubscriberList("url='"+url+"'", "");
			
			for(int i=0; i< numEntries; i++) {  
				Logs logs = getSchedularFacade().getLogs("url='"+url+"'");
				entry[i] = new FeedEntry((SyndEntryImpl)entries[i]);  
			    
				String s;  
				
				if(logs!=null){
					System.out.println("ADA DATA DI TABLE LOG");
					System.out.println(entry[i].getPubdate().toString());
					System.out.println(logs.getPubdate().toString());
					
					if(entry[i].getPubdate().after(logs.getPubdate())){					
						
						s="Title: "+entry[i].getTitle()+newline+  
					      "URL: "+entry[i].getLink()+newline+  
					      "Date: "+entry[i].getPubdate().toString()+newline+entry[i].getDescription()+newline;
						
						System.out.println(i+" :: "+s);
						
						if(subscriberList.size()!=0)
							sendRss(subscriberList,url, entry[i].getLink(), entry[i].getTitle(), entry[i].getDescription(), entry[i].getPubdate());
														
						if(i==(numEntries-1)){
							System.out.println("UPDATE "+entry[0].getPubdate().toString());
							logs.setLink(entry[0].getLink());
							logs.setTitle(entry[0].getTitle());
							logs.setDescription(entry[0].getDescription());
							logs.setPubdate(entry[0].getPubdate());
							logs.setDate(new Date());
							logs.setUrl(url);
							System.out.println("ADD "+entry[0].getPubdate().toString());
							getSchedularFacade().updateLogs(logs);
						}	
						
					}
				}else{
					
					System.out.println("TIDAK ADA DATA LOGS");	
					if(subscriberList.size()!=0)
						sendRss(subscriberList,url, entry[i].getLink(), entry[i].getTitle(), entry[i].getDescription(), entry[i].getPubdate());
					if(i==(numEntries-1)){
						Logs l = new Logs();
						l.setLink(entry[0].getLink());
						l.setTitle(entry[0].getTitle());
						l.setDescription(entry[0].getDescription());
						l.setPubdate(entry[0].getPubdate());
						l.setDate(new Date());
						l.setUrl(url);
						System.out.println("ADD "+entry[0].getPubdate().toString());
						getSchedularFacade().addLogs(l);
					}
				}
				
				
			} 
			
			
			
			
		}  
		catch(Exception e) {  
			System.out.println("Exception in Feedreader: "+e.toString());  
			e.printStackTrace();  
		}  
	}
	
	public void sendRss(List subscriberList, String _url, String _link, String _title, String _description, Date _date){
		for (Iterator iterator = subscriberList.iterator(); iterator.hasNext();) {
			
			Subscriber subscriber = (Subscriber) iterator.next();
			System.out.println("MENGIRIM KE -----------------------------: "+ subscriber.getUsername());			
			
			StringBuffer response = sendNewsResponse(_url, _link, _title, _description, _date.toString());
	        try {
				messaging.sendMessage(subscriber.getUsername()+"@mobbuzz.com", response.toString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public StringBuffer sendNewsResponse(String url, String link, String title, String description, String date){
		StringBuffer news = new StringBuffer();
		news.append("<news>");
		news.append("<url>"+url+"</url>");
		news.append("<link>"+link+"</link>");
		news.append("<title>"+title+"</title>");
		news.append("<description>"+description+"</description>");
		news.append("<date>"+date+"</date>");
		news.append("</news>");
		return news;
	}
	   
}  
